package com.jcl.cloud.services.crawler.brain.task;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jcl.cloud.common.service.util.HttpClientUtil;
import com.jcl.cloud.common.service.util.PageOperation;
import com.jcl.cloud.common.service.util.PageOps;
import com.jcl.cloud.services.brain.common.dto.BuyResumeDataModel;
import com.jcl.cloud.services.crawler.brain.service.RedisService;
import com.jcl.cloud.services.search.common.model.ZlzpBuyResumeModel;
import com.jcl.cloud.services.search.util.SerializeUtils;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ExecuteBuyResumeHandler {

    private final static Logger logger = LoggerFactory.getLogger(ExecuteBuyResumeHandler.class);


    @Autowired
    private RedisService redisService;



    public void executeBuy (BuyResumeDataModel buyResumeDataModel){
        String siteCode = buyResumeDataModel.getSiteCode();
        String crawlerId = buyResumeDataModel.getCrawlerId();

        try {

            String cookieStoreStr = this.redisService.hget("unicrawler:task:info:" + crawlerId, "cookieStore");

            BasicCookieStore cookieStore = SerializeUtils.serializeToObj(cookieStoreStr);
            HttpClientContext context = HttpClientContext.create();
            context.setCookieStore(cookieStore);

            if("zlzp".equalsIgnoreCase(siteCode)){

                List<Cookie> cookieList = cookieStore.getCookies();


                String Cookie = "";
                for (Cookie c : cookieList) {
                    Cookie = Cookie + "; " + c.getName() + "=" + c.getValue();
                }


                Map buyResumeContextMap = buyResumeDataModel.getBuyResumeContext();
                String Referer = (String) buyResumeContextMap.get("Referer");
                String resumeNo = (String) buyResumeContextMap.get("resumeNo");
                String resumeNo_k_t = (String) buyResumeContextMap.get("resumeNo_k_t");

                /***********************************开始购买******************************/
                Map<String,String> buyResumeMap = new HashMap<>();

                buyResumeMap.put("Referer",Referer);
                buyResumeMap.put("Cookie",Cookie);

                String result1 = PageOps.getFolders(context,buyResumeMap);
                logger.info("智联招聘购买简历  result1 = " + result1);


                //获取resumeFolderId
                Integer resumeFolderId = 0;
                JSONObject jo = JSON.parseObject(result1);
                JSONArray ja = jo.getJSONArray("data");
                for(Object o :ja){
                    JSONObject jsonObject = (JSONObject)o;
                    if("未命名文件".equalsIgnoreCase(jsonObject.getString("folderName"))){
                        resumeFolderId = jsonObject.getInteger("id");
                        break;
                    }
                }



                buyResumeMap = new HashMap<>();
                buyResumeMap.put("Referer",Referer);
                buyResumeMap.put("Cookie",Cookie);


                ZlzpBuyResumeModel zlzpBuyResumeModel = new ZlzpBuyResumeModel();
                zlzpBuyResumeModel.setPaymentType("2");
                zlzpBuyResumeModel.setDownloadType("2");

                ZlzpBuyResumeModel.ResumeItem resumeItem = zlzpBuyResumeModel.new ResumeItem();
                resumeItem.setResumeNumber(resumeNo);
                resumeItem.setVersion("1");
                resumeItem.setLang("1");
                String[] label = {"智联白领"};
                resumeItem.setLabel(label);

                ZlzpBuyResumeModel.ResumeItem [] resumeItems = {resumeItem};
                zlzpBuyResumeModel.setResumeItems(resumeItems);

                zlzpBuyResumeModel.setCoupons("");
                zlzpBuyResumeModel.setResumeDownType(0);
                zlzpBuyResumeModel.setFlowId("1");
                zlzpBuyResumeModel.setResumeFolderId(resumeFolderId);





                StringEntity se = new StringEntity(JSON.toJSONString(zlzpBuyResumeModel));


                //{"code":1,"message":"简历已下载","traceId":"82a54bcd358846fcaea83c494d11a43c","bCode":500}
                String result2 = PageOps.doPostToResumeDownload(context,buyResumeMap,se);
                logger.info("智联招聘购买简历  result2 = " + result2);


                buyResumeMap = new HashMap<>();

                buyResumeMap.put("resumeNo",resumeNo_k_t);
                buyResumeMap.put("Referer",Referer);
                buyResumeMap.put("Cookie",Cookie);

                String result3 = PageOps.getResumeDetailForBuy(context,buyResumeMap);
                logger.info("智联招聘购买简历  result3 = " + result3);



                //解析好字段，然后回调

                JSONObject candidateJO = JSON.parseObject(result3).getJSONObject("data").getJSONObject("candidate");


                String name = candidateJO.getString("userName");

                String email = candidateJO.getString("email");
                String mobile = candidateJO.getString("mobilePhone");


                String tenantId = buyResumeDataModel.getTenantId();

                logger.info(String.format("tenantId = %s  , crawlerId = %s 购买获取到的用户信息：name = %s , email = %s  , mobile = %s ",tenantId,crawlerId,name,email,mobile));



                Map map = new HashMap();
                map.put("name",name );
                map.put("email",email );
                map.put("mobile", mobile);
                map.put("tenantId",tenantId );

                //回调
                String ret = HttpClientUtil.doPostJson("http://www.jucailin.com/api/crawler/resume/complete",JSON.toJSONString(map));
                logger.info("智联招聘  获取到详细联系方式后回调接口返回的信息：" + ret);

                /***********************************结束购买******************************/


            }else if("qcwy".equalsIgnoreCase(siteCode)) {
                Map buyResumeContextMap = buyResumeDataModel.getBuyResumeContext();
                String ResumeViewUrl = (String) buyResumeContextMap.get("ResumeViewUrl");

                String result1 = PageOperation.doGet2ResumeView(ResumeViewUrl, context);
                logger.info("前程无忧购买简历   result1=" + result1);

                Document document = Jsoup.parse(result1);
                String userId = document.getElementById("hidUserID").attr("value");



                Map map = new HashMap();
                map.put("userId",userId);
                map.put("Referer",ResumeViewUrl);


                String result2 = PageOperation.doPostToGlobalDownload(map,context);
                logger.info("前程无忧购买简历   result2=" + result2);



                String url = ResumeViewUrl;
                String hidUserID = document.getElementById("hidUserID").attr("value");
                String hidSeqID = document.getElementById("hidSeqID").attr("value");;
                String      hidAccountID = document.getElementById("hidAccountID").attr("value");
                String hidAllSeqIds= document.getElementById("hidAllSeqIds").attr("value");
                String       hidAllUserIds= document.getElementById("hidAllUserIds").attr("value");
                String hidAllAccountIds= document.getElementById("hidAllAccountIds").attr("value");
                String   hidCheckUserIds = document.getElementById("hidCheckUserIds").attr("value");
                String  hidCheckKey  = document.getElementById("hidCheckKey").attr("value");
                String       hidAccessKey= document.getElementById("hidAccessKey").attr("value");
                String hidupt = document.getElementById("hidupt").attr("value");
                String hiddown= document.getElementById("hiddown").attr("value");


                String Referer = ResumeViewUrl;



                map = new HashMap();
                map.put("url",url );
                map.put("hidUserID",hidUserID );
                map.put("hidSeqID",hidSeqID );
                map.put("hidAccountID",hidAccountID );
                map.put("hidAllSeqIds",hidAllSeqIds );
                map.put("hidAllUserIds",hidAllUserIds );
                map.put("hidAllAccountIds",hidAllAccountIds );
                map.put("hidCheckUserIds",hidCheckUserIds );
                map.put("hidCheckKey",hidCheckKey );
                map.put("hidAccessKey",hidAccessKey );
                map.put("hidupt",hidupt );
                map.put("hiddown",hiddown );

                map.put("Referer" ,Referer);


                String result3 = PageOperation.doPost2ResumeView(map,context);
                logger.info("前程无忧购买简历   result3=" + result3);


                document = Jsoup.parse(result3);
                Element nameEle = document.getElementById("tdseekname");
                Element moblieEle = document.select("td[style=white-space:nowrap;]:has(img[src=//img07.51jobcdn.com/imehire/ehire2007/defaultnew/image/resumedetails/y2.png])").first();
                Element emailEle = document.getElementsByAttributeValue("class","blue").first();





                String name = nameEle.text().split("流程")[0];
                String email = emailEle.text();
                String mobile = moblieEle.text();
                String tenantId = buyResumeDataModel.getTenantId();
                logger.info(String.format("前程无忧购买简历  name=%s,email=%s,mobile=%s,tenantId=%s",name,email,mobile,tenantId));


                map = new HashMap();
                map.put("name",name );
                map.put("email",email );
                map.put("mobile", mobile);
                map.put("tenantId",tenantId );

                //回调
                String ret = HttpClientUtil.doPostJson("http://www.jucailin.com/api/crawler/resume/complete",JSON.toJSONString(map));
                logger.info("智联招聘  获取到详细联系方式后回调接口返回的信息：" + ret);


            }
        } catch (Exception e) {
             logger.error(String.format("crawlerId = %s ，taskType = %s 的购买简历任务发生异常：%s",crawlerId,siteCode,e.getMessage()),e);
        }
    }



}
